﻿using Controler;
using System;
using System.IO;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Worker
{
    class BingImg
    {
        static XmlHelper xmlHelper = new XmlHelper();
        static string dicPath = xmlHelper.Read(Setting.SaveImgPath);
        private static readonly string _PATH = $"{dicPath}{DateTime.Now.ToString("yyyyMMdd")}{xmlHelper.Read(Setting.ImgType)}";

        [DllImport("user32.dll", EntryPoint = "SystemParametersInfo", SetLastError = true)]
        public static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni);

        public static void Do()
        {
            if (!Directory.Exists(dicPath))
            {
                Directory.CreateDirectory(dicPath);
            }
            var url = GetImgUrl();
            var content = GetResponse(url).Result.Content.ReadAsByteArrayAsync().Result;
            SaveImg(content);
            SystemParametersInfo(20, 0, _PATH, 1);
        }


        public static string GetImgUrl()
        {
            var content = GetResponse(xmlHelper.Read(Setting.BingUrl)).Result.Content.ReadAsStringAsync().Result;
            string pattern = xmlHelper.Read(Setting.ImgRegex);
            var regex = new Regex(pattern);
            return $"{xmlHelper.Read(Setting.BingUrl)}{regex.Match(content)}";
        }

        public static async Task<HttpResponseMessage> GetResponse(string url)
        {
            using (var httpClient = new HttpClient())
            {
                return await httpClient.GetAsync(url);
            }
        }

        public static void SaveImg(byte[] content)
        {
            using (var fs = new FileStream(_PATH, FileMode.Create))
            {
                fs.Write(content, 0, content.Length);
            }
        }
    }
}